package com.fiveGroup.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fiveGroup.pojo.Cart;
import com.fiveGroup.pojo.CartProduct;
import com.fiveGroup.pojo.vo.CartVo;
import com.fiveGroup.pojo.vo.DataVo;
import com.fiveGroup.service.CartProductService;
import com.fiveGroup.service.CartService;
import com.fiveGroup.util.UserContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 购物车控制器
 */
@RestController
@RequestMapping("/api/cart")
public class CartController {

    @Autowired
    private CartService cartService;
    @Autowired
    private CartProductService cartProductService;

    /**
     * 查询当前用户的购物车列表（关联商品信息）
     *
     * @return 包含购物车列表的DataVO
     */
    @GetMapping("/list")
    public DataVo<List<CartVo>> getCartList() {
        List<CartVo> cartVOList = cartService.selectCartWithProduct(UserContextHolder.getUserId());
        return DataVo.success(cartVOList);
    }

    /**
     * 移除购物车中的商品
     *
     * @param cartVo 购物车记录ID
     * @return 操作结果的DataVO
     */
    @DeleteMapping("/remove")
    public DataVo<Void> removeCartItem(@RequestBody CartVo cartVo) {
        try {
            QueryWrapper<CartProduct> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("cart_id", cartVo.getId());
            queryWrapper.eq("product_id", cartVo.getProductId());
            boolean isDeleted = cartProductService.remove(queryWrapper);

            if (isDeleted) {
                return DataVo.success();
            } else {
                return DataVo.fail(400, "移除失败，购物车记录不存在");
            }
        } catch (Exception e) {
            return DataVo.fail(500, "移除购物车失败：" + e.getMessage());
        }
    }

    @PostMapping("/add")
    public DataVo addCartItem(@RequestBody CartVo cartvo) {
        Long id = UserContextHolder.getUserId();
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", id);
        Cart cartByDb = cartService.getOne(queryWrapper);

        if (cartByDb != null) { //存在用户购物车
            CartProduct cartProduct = new CartProduct();
            QueryWrapper<CartProduct> queryWrapper1 = new QueryWrapper<>();
            //判断是否重复添加
            queryWrapper1.eq("cart_id", cartByDb.getId());
            queryWrapper1.eq("product_id", cartvo.getProductId());
            if (cartProductService.exists(queryWrapper1)) return DataVo.fail("请勿重复添加");
            cartProduct.setCartId(cartByDb.getId());
            cartProduct.setProductId(cartvo.getProductId());
            cartProductService.save(cartProduct);
        } else { //不存在用户购物车--创建
            Cart cart = new Cart();
            cart.setUserId(UserContextHolder.getUserId());
            cart.setCreatedAt(new Date());
            cartService.save(cart);

            CartProduct cartProduct = new CartProduct();
            cartProduct.setCartId(cart.getId());
            cartProduct.setProductId(cartvo.getProductId());
            cartProductService.save(cartProduct);
        }
        return DataVo.success();
    }

}
